<template>
  <a-drawer
    :title="titleShow"
    :maskClosable="true"
    :visible="visible"
    :destroyOnClose="true"
    :width="width ? width : '1027px'"
    :body-style="{ paddingBottom: '60px' }"
    @close="closeModal"
  >
    <a-spin tip="加载中..." :spinning="spinning">
      <section class="content">
        <!-- tabs -->
        <a-tabs
          v-model:activeKey="activeKey"
          size="small"
          style="margin-bottom: 16px"
        >
          <a-tab-pane
            v-for="tab of tabList"
            :key="tab.key"
            :tab="tab.title"
          ></a-tab-pane>
        </a-tabs>
        <!-- contents -->
        <template v-if="currentContent">
          <section v-show="currentContent.type == 'copy'">
            <template v-if="currentContent.data && currentContent.data.length">
              <!-- 说明 -->
              <Alert
                v-if="currentContent.showAlert"
                message="说明"
                type="info"
                closable
                class="mb-20"
                :after-close="
                () => {
                  currentContent.showAlert = false;
                }
              "
              >
                <template #description>
                  <p
                    v-for="(remark, remarkIndex) of currentContent.remark"
                    :key="remarkIndex"
                  >
                  <span v-if="currentContent.remark.length > 1">{{
                      remarkIndex + 1 + "、"
                    }}</span>
                    {{ remark }}
                  </p>
                </template>
              </Alert>
              <!-- 关键词 -->
              <card-item :content="currentContent.data" @changeTableField="changeTableField" :tableFields="modelRef.table_fields" :key="tableKeys"/>
            </template>
          </section>
          <section v-show="currentContent.type == 'form'">
            <!-- 表单 -->
            <a-form layout="vertical">
              <a-form-item
                :label="title + '名称'"
                v-bind="validateInfos.template_name"
              >
                <a-input
                  placeholder="请输入"
                  v-model:value="modelRef.template_name"
                />
              </a-form-item>

              <a-form-item
                label="合同类型"
                v-bind="validateInfos.scene"
                v-if="title == '合同打印模版'"
              >
                <a-select v-model:value="modelRef.scene" placeholder="请选择">
                  <a-select-option :value="'normal'">正式合同</a-select-option>
                  <a-select-option :value="'purpose'">意向合同</a-select-option>
                </a-select>
              </a-form-item>

              <a-form-item label="上传模板" v-bind="validateInfos.template_path">
                <a-row
                  justify="space-between"
                  class="file-list"
                  v-if="fileName && id"
                  @click="previewClick"
                >
                  <a-col>
                    <a-space>
                      <LinkOutlined />
                      <a>{{ fileName }}</a>
                    </a-space>
                  </a-col>
                </a-row>
                <a-upload-dragger
                  v-model:fileList="fileList"
                  name="file"
                  :multiple="false"
                  :showUploadList="false"
                  :action="$utils.fileAction"
                  :headers="{ 'org-token': $store.getters.token }"
                  @change="handleUploadChange"
                  accept=".docx"
                  :data="{
                  dir: 'org_contract_leases',
                  scene: 'contractTemplate',
                }"
                  @preview="previewClick"
                >
                  <template v-if="fileList.length">
                    <p class="ant-upload-drag-icon">
                      <FileTextOutlined />
                    </p>
                    <p class="ant-upload-text">
                      {{ fileList[0].name }}
                    </p>
                  </template>
                  <template v-else>
                    <p class="ant-upload-drag-icon">
                      <InboxOutlined />
                    </p>
                    <p class="ant-upload-text">
                      拖拽文件至虚线款内或点击此区域上传文件
                    </p>
                    <p class="ant-upload-hint">文档只支持docx格式</p>
                  </template>
                </a-upload-dragger>
              </a-form-item>
              <a-form-item
                label="选择楼宇"
                v-bind="validateInfos.relation_builds"
              >
                <a-alert
                  v-if="disabledTree"
                  show-icon
                  type="warning"
                  message="该审批流程原来绑定的项目/楼宇，您未全部选中，无法修改。"
                  class="mb-10"
                />
                <ChooseHousingResources
                  checkType="build"
                  :allDisabled="disabledTree"
                  :defaultChecked="{ buildList: checkedBuildList }"
                  @request="$utils.commonRequest"
                  @getResult="getResult"
                  @error="setCheckedError"
                />
              </a-form-item>
            </a-form>
          </section>
        </template>
      </section>
    </a-spin>

    <div class="drawer-footer">
      <a-button @click.prevent="closeModal" class="mr-10">关闭</a-button>
      <a-button type="primary" @click.prevent="onSubmit" :loading="submiting">
        保存
      </a-button>
    </div>

    <!-- 预览 -->
    <ElectronContractModal
      :visible="electronContractVisible"
      :urlData="previewUrlData"
      :esignDetail="{
        esignCheck: true,
      }"
      title="在线预览"
      @close="electronContractVisible = false"
    />
  </a-drawer>
</template>

<script>
import { defineComponent, ref, computed, watch, reactive, toRaw } from "vue";
import { Form, message, Alert } from "ant-design-vue";
import request from "../../../../common/utils/request";
import store from "../../../../store";
import utils from "../../../../common/utils/utils";
import CardItem from "./CardItem.vue";
import {
  InboxOutlined,
  FileTextOutlined,
  LinkOutlined,
} from "@ant-design/icons-vue";
import { ChooseHousingResources } from "bl-common-vue3";

import ElectronContractModal from "../../../../components/ElectronContractModal/index.vue";
import _ from "lodash";

const useForm = Form.useForm;

export default defineComponent({
  name: "clauseTypeAdd",
  components: {
    CardItem,
    ChooseHousingResources,
    Alert,
    InboxOutlined,
    FileTextOutlined,
    ElectronContractModal,
    LinkOutlined,
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    title: {
      type: String,
      default: "",
    },
    id: {
      type: [String, Number],
      default: 0,
    },
    pageForm: {
      type: String,
      default: "",
    },
    tabList: {
      type: Array,
      default: () => {
        return [];
      },
    },
    width: {
      type: String,
      default: "",
    },
  },
  setup(props, context) {
    const titleShow = computed(() => {
      return (props.id ? "编辑" : "新建") + props.title;
    });

    const activeKey = ref("");
    const tableKeys = ref(0);
    const spinning = ref(false);

    const currentContent = ref();
    const actionMap = {
      lease: {
        action: "GetLeaseTempTags",
        showBuilding: true,
        submitUrl: "/contract/retreatContractAdd",
      },
      print: {
        action: "GetPrintTempTags",
        showBuilding: true,
        submitUrl: "/contract/contractPrintAdd",
        detailUrl: "/contract/printTemplateDetail",
        detailSubmitUrl: "/contract/printContractEdit",
      },
      notice: {
        action: "GetNoticePrintTags",
        showBuilding: true,
        submitUrl: "/notice/templateAdd",
        detailUrl: "/notice/templateDetail",
        detailSubmitUrl: "/notice/templateEdit",
      },
    };

    const disabledTree = ref(false);
    const checkedBuildList = ref([]);

    const setCheckedError = (e) => {
      disabledTree.value = true;
    };

    const getResult = (info) => {
      if (disabledTree.value) {
        return;
      }
      const { villageList, buildList } = info;
      let list = [];
      if (villageList.length) {
        for (let village of villageList) {
          list = [...list, ...village.children];
        }
      }
      if (buildList.length) {
        list = [...list, ...buildList];
      }
      checkedBuildList.value = list;
    };

    watch(activeKey, (val) => {
      if (val) {
        const current = props.tabList.find((item) => item.key == val);
        console.log(current, "currentcurrent");
        if (current.type == "copy") {
          store
            .dispatch(actionMap[props.pageForm].action, {
              key: current.key,
              requestData: current.request,
            })
            .then((data) => {
              current.data = data;
              setCurrentContent(current);
            });
          return;
        }
        if (actionMap[props.pageForm].showBuilding) {
          modelRef.relation_builds = modelRef.relation_builds || null;
          rulesRef.relation_builds = [
            { required: true, message: "请勾选关联楼宇" },
          ];
        } else {
          delete modelRef.relation_builds;
          delete rulesRef.relation_builds;
        }
        setCurrentContent(current);
        return;
      }
    });

    const setCurrentContent = (content) => {
      currentContent.value = content;
      currentContent.value.showAlert =
        currentContent.value.showAlert ||
        (content.remark && content.remark.length);
    };

    /**
     * @description:  表单
     */
    const modelRef = reactive({
      template_name: "",
      template_path: "",
      scene: null, //合同类型。【ID1014427】意向合同 需求新增字段
      table_fields: {}, // 选择的表格字段
      relation_builds: null,
    });

    const scene_rule = computed(() => {
      let rule = [{ required: false, message: "请选择合同类型" }];
      if (props.title == "合同打印模版") {
        rule = [{ required: true, message: "请选择合同类型" }];
      }
      return rule;
    });

    const rulesRef = reactive({
      template_name: [{ required: true, message: "请输入模板名称" }],
      template_path: [{ required: true, message: "请上传模板" }],
      scene: scene_rule,
    });

    const { resetFields, validate, validateInfos } = useForm(
      modelRef,
      rulesRef
    );
    const fileList = ref([]);
    const fileName = ref("");
    const handleUploadChange = (info) => {
      let resFileList = [...info.fileList];
      if (resFileList.length) {
        resFileList = resFileList.slice(-1);
        resFileList = resFileList.map((file) => {
          if (file.response) {
            if (file.response.code == 1000) {
              file.url = file.response.data.fileUrl;
              file.previewUrl = file.response.data.previewUrl;
              modelRef.template_path = file.url;
              fileName.value = file.name;
            } else {
              message.warning(file.response.msg);
            }
          }
          return file;
        });
      } else {
        modelRef.template_path = "";
        fileName.value = "";
      }
      fileList.value = resFileList;
    };

    // 预览
    const electronContractVisible = ref(false);
    const previewUrlData = ref({});
    const previewClick = () => {
      if (props.id) {
        previewUrlData.value = {
          previewUrl: fileList.value[0].previewUrl,
          url: fileList.value[0].url,
        };
        electronContractVisible.value = true;
        return;
      }
      previewUrlData.value = {
        previewUrl: fileList.value[0].previewUrl,
        url: fileList.value[0].url,
      };
      electronContractVisible.value = true;
    };

    const changeTableField = (name, list) => {
      modelRef.table_fields[name] = list;
    };

    // const beforeUpload = (file) => {
    //   return new Promise((resolve, reject) => {
    //     console.log("beforeUpload", file);
    //     const isAccept = [
    //       ".doc",
    //       ".docx",
    //       "application/wps-write",
    //       // word 2007以上的type
    //       "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
    //       "application/msword",
    //     ].includes(file.type);
    //     if (!isAccept) {
    //       message.error("只支持.doc、.doc、docx格式的文件上传！");
    //       reject();
    //     }
    //     resolve();
    //   });
    // };

    const closeModal = () => {
      context.emit("onCancel");
    };

    const submiting = ref(false);
    const onSubmit = () => {
      if (actionMap[props.pageForm].showBuilding) {
        if (!disabledTree.value && checkedBuildList.value.length) {
          modelRef.relation_builds = utils.getProjectBuildByBuildList(
            checkedBuildList.value
          );
        }
        if (modelRef.relation_builds) {
          // 通知单打印模板
          if (actionMap[props.pageForm].action == "GetNoticePrintTags") {
            modelRef.name = modelRef.template_name;
            modelRef.build_bind = modelRef.relation_builds;
            delete modelRef.template_name;
            delete modelRef.relation_builds;
          } else {
            modelRef.relation_builds = JSON.stringify(modelRef.relation_builds);
          }
        }
      }
      setTimeout(() => {
        validate().then(() => {
          submiting.value = true;
          let params = { ...modelRef, needMsg: true };

          // 【ID1014427】意向合同 需求新增字段，需要传合同类型
          if (props.title != "合同打印模版") {
            delete params.scene;
          }
          let requestMethods = "post";
          let requestUrl = actionMap[props.pageForm].submitUrl;
          if (props.id) {
            params.id = props.id;
            requestMethods = "put";
            requestUrl = actionMap[props.pageForm].detailSubmitUrl;
          }
          console.log("onSubmit", params);
          const success = (res) => {
            message.success(res.msg || "保存成功");
            context.emit("success");
          };
          request[requestMethods]("/org", requestUrl, params)
            .then((res) => success(res))
            .finally(() => {
              submiting.value = false;
            });
        });
      }, 0);
    };

    let detail = null;
    const getDetail = () => {
      const url = actionMap[props.pageForm].detailUrl;
      if (url) {
        spinning.value = true;
        request
          .get("/org", url, {
            id: props.id,
          })
          .then((res) => {
            detail = res.detail;

            delete modelRef.template_path;
            // 通知单打印模板
            if (actionMap[props.pageForm].action == "GetNoticePrintTags") {
              modelRef.template_name = detail.name;
            } else {
              modelRef.template_name = detail.template_name;
            }
            if (detail.template_path) {
              modelRef.template_path = detail.template_path;
              fileList.value = [
                {
                  uid: "1",
                  url: detail.template_path,
                  name:
                    actionMap[props.pageForm].action == "GetNoticePrintTags"
                      ? detail.name
                      : detail.template_name,
                },
              ];
              if (detail.online_preview) {
                fileList.value[0].previewUrl = detail.online_preview.previewUrl;
              }
              fileName.value =
                actionMap[props.pageForm].action == "GetNoticePrintTags"
                  ? detail.name
                  : detail.template_name;
            }
            if (detail?.table_fields) {
              let tableFields = {};
              Object.keys(detail.table_fields).forEach((key) => {
                tableFields[key] = detail.table_fields[key].map((v) => {
                  v.isDetail = true;
                  return v;
                });
              })
              modelRef.table_fields = _.cloneDeep(tableFields);
              tableKeys.value ++;
            }
            if (actionMap[props.pageForm].showBuilding) {
              modelRef.relation_builds = null;
              rulesRef.relation_builds = [
                { required: true, message: "请勾选关联楼宇" },
              ];
              if (props.id) {
                if (detail.relation_builds) {
                  checkedBuildList.value = detail.relation_builds.buildId.map(
                    (id) => ({
                      id,
                    })
                  );
                  modelRef.relation_builds = detail.relation_builds;
                } else if (
                  actionMap[props.pageForm].action == "GetNoticePrintTags"
                ) {
                  // 通知单打印模板
                  checkedBuildList.value = detail.build_bind.buildId.map(
                    (id) => ({ id })
                  );
                  modelRef.relation_builds = detail.build_bind;
                }
              }
            } else {
              delete modelRef.relation_builds;
              delete rulesRef.relation_builds;
            }
            if (props.title == "合同打印模版" && detail.scene) {
              modelRef.scene = detail.scene;
            }
            spinning.value = false;
          });
      }
    };

    // 初始化
    const init = () => {
      activeKey.value = props.tabList[0].key;
      if (props.id) {
        getDetail();
      }
    };

    watch(
      () => props.visible,
      (val) => {
        if (val) {
          init();
        } else {
          resetFields();
          fileList.value = [];
          checkedBuildList.value = [];
          disabledTree.value = false;
          fileName.value = "";
          tableKeys.value = 0;
          spinning.value = false;
        }
      }
    );

    return {
      titleShow,
      activeKey,
      currentContent,
      modelRef,
      validateInfos,
      submiting,
      fileList,
      closeModal,
      onSubmit,
      handleUploadChange,
      checkedBuildList,
      getResult,
      setCheckedError,
      disabledTree,
      previewClick,
      previewUrlData,
      electronContractVisible,
      fileName,
      tableKeys,
      changeTableField,
      spinning,
    };
  },
});
</script>

<style lang="less" scoped>
.ant-upload-text {
  color: @primary-color !important;
}
.file-list {
  cursor: pointer;
  padding: 1px 5px;
  margin-bottom: 10px;
}
.file-list:hover {
  background: #f5f5f5;
  transition: 0.5s ease;
}
</style>
